package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import worklog.Holidays;
import worklog.dto.ResponseDTO;

@WebServlet("/holidays")
public class HolidaysServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ResponseDTO responder = new ResponseDTO();
	
    public HolidaysServlet() throws Exception{ super(); }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	out.print(processRequest(request));
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
    	String yearStr = request.getParameter("y");
    	String shortJson = request.getParameter("short");
        
    	if (yearStr == null || yearStr.length() <= 1) return responder.showError("Incorrect parameters");
    	int year;
    	try{ year = Integer.parseInt(yearStr); }
    	catch(Exception e){ return responder.showError("Incorrect parameters"); }

    	Holidays holis = new Holidays(year);
    	if (shortJson != null) return holis.toJson();
    	else return holis.toString();
	}
	
}